import json

from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response
from curriculum.models import Course, CourseTag, Chapter, CourseNode, Follow, UserSections, Comment, CommentReply
from goods.models import Sections
from syl_ideal import settings
from django.core.paginator import InvalidPage, Paginator
from haystack.forms import ModelSearchForm
from django.http import JsonResponse, HttpResponse

RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 15)
# Create your views here.
from curriculum.serializers import CourseSerializer, \
    CourseTagializer, ChapterSerializer, CourseNodeSerializer, \
    FollowSerializer, UserSectionsSerializer, SectionsSerializer, CommentSerializer, CommentReplySerializer


# 自定义分页器 局部
class PageNum(PageNumberPagination):
    # 查询字符串中代表每页返回数据数量的参数名, 默认值: None,也就是一页返回多少条数据
    page_size_query_param = 'page_size'
    # 查询字符串中代表页码的参数名, 有默认值: page，第几页
    page_query_param = 'page'
    # 一页中最多的结果条数
    max_page_size = 16


# CourseNode
class CourseNodeView(viewsets.ModelViewSet):
    # 自定义权限类
    permission_classes = (AllowAny,)
    queryset = CourseNode.objects.all()
    serializer_class = CourseNodeSerializer
    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序
    # 指定过滤字段, 不设置, 过滤功能不起效
    # filter_fields = ('id', 'curriculum')


class TagView(viewsets.ModelViewSet):
    # 自定义权限类
    permission_classes = (AllowAny,)
    queryset = CourseTag.objects.all()
    serializer_class = CourseTagializer
    # 指定过滤字段, 不设置, 过滤功能不起效
    # filter_fields = ('id', 'course_tag')


# Chapter
class ChapterView(viewsets.ModelViewSet):
    # 自定义权限类
    permission_classes = (AllowAny,)
    queryset = Chapter.objects.all()
    serializer_class = ChapterSerializer
    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序
    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('id', 'course')


class ShowCourse(viewsets.ModelViewSet):
    '''用户注册，权限是，匿名用户可以访问'''
    # 自定义权限类
    permission_classes = (AllowAny,)
    queryset = Course.objects.all()
    serializer_class = CourseSerializer

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('create_time', 'update_time', 'follows')

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('course_tag', 'status', 'phases', 'id')

    pagination_class = PageNum

class SectionsViewSet(viewsets.ModelViewSet):
    permission_classes = (AllowAny,)
    queryset = Sections.objects.all()
    serializer_class = SectionsSerializer

class PathShow(APIView):
    # 自定义权限类
    permission_classes = (AllowAny,)

    def get(self, request):
        id = request.query_params.get('pid')
        print(id)
        coures = Course.objects.filter(phases=id)
        print(coures)
        ser = CourseSerializer(coures, many=True)
        return Response({"code": '200', 'msg': ser.data})


# 关注课程
class AddFollow(APIView):
    # 自定义权限类
    permission_classes = (AllowAny,)

    def post(self, request):
        # 获取参数，user_id,coures_id, action:取消/关注
        uid = request.user.id
        cid = request.data.get('cid')
        action = request.data.get('action')
        # 关注，修改follow表，修改课程关注人数
        if action == '1':
            try:
                follow = Follow.objects.get(user_id=uid, curriculum_id=cid)
            except Exception as e:
                follow = None
            # 如果查询到数据已存在，证明关注过
            if follow:
                return Response({'code': 0, 'msg': '关注成功'})
            # 如果数据不存在，动作又是关注的动作，那么就添加关注记录
            else:
                follow = Follow(user_id=uid, curriculum_id=cid)
                follow.save()
                # 根据外键关联到课程表，点出来关注字段，关注数量加1
                follow.curriculum.follows += 1
                follow.curriculum.save()
                return Response({'code': 0, 'msg': '关注成功'})
        else:
            # 取消关注
            follow = Follow.objects.get(user_id=uid, curriculum_id=cid)

            # 根据外键关联到课程表，点出来关注字段，关注数量减去1
            follow.curriculum.follows -= 1
            follow.curriculum.save()
            # 取消关注，删除关注记录
            follow.delete()
            return Response({'code': 0, 'msg': '取关成功'})


# 关注
class FollowViewSet(viewsets.ModelViewSet):
    queryset = Follow.objects.all()
    serializer_class = FollowSerializer

    permission_classes = (AllowAny,)

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('create_time',)

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('user',)

    # 自定义分页器 覆盖全局配置
    pagination_class = PageNum


# 观看历史
class UserSectionsViewSet(viewsets.ModelViewSet):
    queryset = UserSections.objects.all()
    serializer_class = UserSectionsSerializer

    permission_classes = (AllowAny,)

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('create_time',)

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('user', 'course')

    # 自定义分页器 覆盖全局配置
    pagination_class = PageNum


# 播放记录
class AddPlayHistory(APIView):
    permission_classes = (AllowAny,)

    def post(self, request):
        # 1. 获取用户, 获取小节id
        user = request.user
        print('user',user)
        sid = request.data.get('sid')
        print('这个sid',sid)
        section = Sections.objects.filter(id=sid)
        print('section:',section)

        course = section.chapters.course
        print('course:',course)

        # 2. 保存播放记录
        try:
            us = UserSections.objects.get(user=user, course=course, section=section)
        except Exception as e:
            us = None
        if us:
            us.save()  # 更新updatetime
            return Response({"code": 0, "msg": "添加播放记录成功"})
        else:
            us = UserSections(user=user, course=course, section=section)
            us.save()
            return Response({"code": 0, "msg": "添加播放记录成功"})


# 全文检索
def course_index_search(request):
    query = request.GET.get('q', None)
    page = int(request.GET.get('page', 1))
    page_size = int(request.GET.get('page_size', RESULTS_PER_PAGE))
    if query:
        form = ModelSearchForm(request.GET, load_all=True)
        if form.is_valid():
            results = form.search()
        else:
            results = []
    else:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    paginator = Paginator(results, page_size)
    try:
        page = paginator.page(page)
    except InvalidPage:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    jsondata = []
    for result in page.object_list:
        data = {
            'id': result.object.id,
            'title': result.object.title,
            'desc': result.object.desc,
            'img': request.scheme + '://' + request.META['HTTP_HOST'] + result.object.img.url,
            'follower': result.object.follows,
            'learner': result.object.learner,
            'status': result.object.status,
            'course_type': result.object.course_type.id
        }
        jsondata.append(data)
    result = {
        "code": 200,
        "msg": 'Search successfully！',
        "data": {"count": page.paginator.count, "results": jsondata}
    }
    # return JsonResponse(result)
    # 返回中文
    return HttpResponse(json.dumps(result, ensure_ascii=False), content_type='application/json')




class CommentReplyViewSet(viewsets.ModelViewSet):
    queryset = CommentReply.objects.all()
    serializer_class = CommentReplySerializer

    permission_classes = (AllowAny,)

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('create_time',)

    # 指定过滤字段, 不设置, 过滤功能不起效
    # filter_fields = ('user', 'course')

    # 自定义分页器 覆盖全局配置
    # pagination_class = PageNum


class CommentViewSet(viewsets.ModelViewSet):
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer

    permission_classes = (AllowAny,)

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('create_time',)

    # 指定过滤字段, 不设置, 过滤功能不起效
    # filter_fields = ('user', 'course')











# class ShowCourse(APIView):
#     def get(self, request):
#         curriculum = Course.objects.all()
#
#         alist = []
#         for i in curriculum:
#             print(i.img)
#             data = {
#                 'title': i.title,
#                 'desc': i.desc,
#                 'logo': i.img,
#                 'create_time': i.create_time,
#                 'update_time': i.update_time
#
#             }
#             alist.append(data)
#
#         print(alist)
#         return Response({'code': 200, 'data': alist})
